import { getRequestKey } from '../utils/baseUrl'
import { getRetails } from '../utils/localStore'
import store from '@/store'

export function setSha(str) {
  const sha256 = require('js-sha256').sha256
  return sha256(str)
}

export function getSha256Sign(callTime, random) {
  // console.log('sign key : ' + getRequestKey())
  const str = 'callTime=' + callTime + '&nonce=' + random + '&systemId=storecenter&' + getRequestKey()
  return setSha(str)
}

export function randomWord() {
  let str = ''
  const arr = [
    '0',
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    'a',
    'b',
    'c',
    'd',
    'e',
    'f',
    'g',
    'h',
    'i',
    'j',
    'k',
    'l',
    'm',
    'n',
    'o',
    'p',
    'q',
    'r',
    's',
    't',
    'u',
    'v',
    'w',
    'x',
    'y',
    'z',
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
    'G',
    'H',
    'I',
    'J',
    'K',
    'L',
    'M',
    'N',
    'O',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'U',
    'V',
    'W',
    'X',
    'Y',
    'Z'
  ]

  for (let i = 0; i < 16; i++) {
    const pos = Math.round(Math.random() * (arr.length - 1))
    str += arr[pos]
  }
  return str
}

export function getTime() {
  return new Date().Format('yyyyMMddhhmmssS')
}

// dom对象转义
export function stringEncode(str) {
  var div = document.createElement('div')
  if (div.innerText) div.innerText = str
  else div.textContent = str
  return div.innerHTML
}

export function GetQueryValue(name) {
  // var reg = new RegExp('(\\?|&)' + name + '=([^&]*)(&|$)', 'i')
  // var r = window.location.href['match'](reg)
  // if (r != null) {
  //   return unescape(r[2])
  // }
  // return null
  const herf = stringEncode(window.location.href)
  const index = herf.indexOf('?')
  const url = herf.slice(index)
  const theRequest = {}
  if (url.indexOf('?') !== -1) {
    const str = url.substr(1)
    const strs = str.split('&')
    for (let i = 0; i < strs.length; i++) {
      theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
    }
  }
  return theRequest[name] || null
}

export function toPortal() {
  let retails = getRetails()
  if (retails === undefined) {
    retails = GetQueryValue('retails')
  }
  const APPID = store.state.user.appIdLogin
  let mark = '?'
  if (location.href.includes('?')) mark = '&'
  const target = encodeURIComponent(`${location.href}${mark}appId=${APPID}`)
  const params = retails ? `retails=${retails}&target=${target}` : `target=${target}`
  location.href = `${window.appConfig.SSO_API}?${params}`
}
